package com.kede.api.order.schedu;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.kede.domain.LeescoreOrderDomain;
import com.kede.domain.LeescoreOrderGoodsDomain;
import com.kede.ienum.order.OrderStatusEnum;
import com.kede.ienum.order.PayStatusEnum;
import com.kede.service.LeescoreOrderGoodsService;
import com.kede.service.LeescoreOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.List;

/***
 ** @Author:Pr.li
 ** @Description: 德币商城订单定时
 ** @Date: create in 2023/5/22 11:37
 ***/
@EnableScheduling
@Component
@Slf4j
public class OrderEffectSchedu {

    @Resource
    private LeescoreOrderService leescoreOrderService;

    @Resource
    private LeescoreOrderGoodsService orderGoodsService;

    private static int defaultZeno = 0;

    /**
     * 定时取消过期订单
     **/
    @Scheduled(cron = "1 1 1 * * *")
    @Transactional(rollbackFor = Exception.class)
    public void cancelOrder(){
        log.debug("cancelOrder执行了");
        LambdaQueryWrapper<LeescoreOrderDomain> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.gt(LeescoreOrderDomain::getEffectTime,defaultZeno);
        queryWrapper.eq(LeescoreOrderDomain::getPay, PayStatusEnum.NOPAY.getEnumIndex());
        List<LeescoreOrderDomain> list = leescoreOrderService.list(queryWrapper);
        log.debug("定时获取的list=={}",list);
        long l = LocalDateTime.now().toEpochSecond(ZoneOffset.ofHours(8));
        for (LeescoreOrderDomain orderDomain : list) {
            //这个单已经过了有效期
            if ((orderDomain.getEffectTime().longValue() < l)) {
                orderDomain.setStatus(OrderStatusEnum.CANCEL);
                orderDomain.setEffectTime(defaultZeno);
                //释放商品库存
                log.debug("定时释放库存");
                log.debug("orderid==={}",orderDomain.getId());
                try {
                    leescoreOrderService.updateById(orderDomain);
                    orderGoodsService.backOrderGoodsByOrderId(orderDomain.getId());
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
    }

}
